import {action, mutation} from '../../../../common/quantity'
import SQLite from '../../../../common/SQLiteHelper'
import preplanServer from '../../../../server/preplan/preplanServer'
import commonSqlHelper from '../../../../server/common/commonSqlHelper'
import L from '../../../../common/localStore'
import evidenceCatalogTree from '../../../../config/evidenceCatalogTree'

const uuid = require('uuid/v4')
const fs = require('fs')
const path = require('path')

const {
  util: {copyFileSync, getCatalogML}
} = require('../../../../util')

// import SQLite from "../../../common/SQLiteHelper";

const state = {
  // evidenceCatalog: [],//示证目录数据源
  evidenceCatalogTreeData: [], // 示证目录树形数据
  evidenceCatalogRecycleBinData: [], // 示证目录回收站
  catalogTemplate: [], // 模板列表
  defaultChapterTemplate: '270e6157-a4fb-6c3a-0a13-c700542f81a9'
}

const mutations = {
  [mutation.preplan.initPrePlan] (state, data = []) {
    // 示证目录

    if (!data.length) return (state.evidenceCatalogTreeData = data)

    let defaultChapterTemplate = localStorage.getItem('defaultChapterTemplate')
    if (defaultChapterTemplate) state.defaultChapterTemplate = defaultChapterTemplate

    if (!state.evidenceCatalogTreeData.length) return (state.evidenceCatalogTreeData = data)

    let caseName = this.state.appearCourt.caseInfo.AJMC

    let _data = data.find((item) => item.name === caseName)
    let _evidenceCatalogTreeData = state.evidenceCatalogTreeData.find((item) => item.name === caseName)

    if (_evidenceCatalogTreeData && _data) {
      _evidenceCatalogTreeData.children = _data.children
    }

    // state.evidenceCatalogTreeData = data;
    // fs.writeFileSync('evidenceCatalogTreeData.json', JSON.stringify(data, null, 2));
  },
  [mutation.preplan.SET_CATALOGTEMPLATE] (state, payload) {
    state.catalogTemplate = payload
  },
  [mutation.preplan.SetChapterTemplate] (state, value) {
    state.defaultChapterTemplate = value
    localStorage.setItem('defaultChapterTemplate', value)
  },
  [mutation.preplan.addRecycleBinData] (state, recycleBinDataObj) {
    state.evidenceCatalogRecycleBinData.push(recycleBinDataObj)
  },
  [mutation.preplan.setRecycleBinData] (state, recycleBinDataObjs) {
    state.evidenceCatalogRecycleBinData = recycleBinDataObjs
  },
  [mutation.preplan.clearRecycleBinData] (state, recycleBinData) {
    let index = state.evidenceCatalogRecycleBinData.findIndex((item) => item.id === recycleBinData.id)
    if (index > -1) state.evidenceCatalogRecycleBinData.splice(index, 1)
  }
}

const actions = {
  async [action.preplan.initEvidenceCatalog] ({commit, rootState, state}, data = []) {
    try {
      let rootNode = data
      if (!rootNode.length) {
        rootNode = {
          id: uuid(),
          pid: '-1',
          name: rootState.appearCourt.caseInfo.AJMC,
          type: 0,
          alias: rootState.appearCourt.caseInfo.AJMC,
          suffix: '',
          stream: [],
          comment: '',
          order: 0,
          fileType: '',
          fileID: '',
          style: '',
          template: '',
          children: []
        }

        let templateData = L.LocalStore.getTemplateData()
        templateData = templateData || []
        let filter = templateData.filter((x) => x.default)

        if (filter.length) {
          data = filter[0].data
        } else {
          let template = JSON.parse(JSON.stringify(state.catalogTemplate.find((x) => x.inlay)))
          if (template) {
            data = template.data
          } else {
            data = state.catalogTemplate.length ? JSON.parse(JSON.stringify(state.catalogTemplate[0])) : []
          }
        }
        data.forEach((item) => (item.pid = rootNode.id))
        rootNode.children = data
        rootNode = [rootNode]
      }
      console.log(111)
      // console.log(JSON.stringify(rootNode))
      await preplanServer.addEvidenceCatalog(JSON.stringify(rootNode))
      commit(mutation.preplan.initPrePlan, rootNode)
    } catch (error) {
      console.log(error)
    }
  },
  async [action.preplan.initPrePlan] ({commit, dispatch, rootState}, data) {
    try {
      // 示证目录回收站
      let recycleBinDataObjs = await SQLite.ExecuteReader({
        SQL: `select * from yx_ya_hsz`
      })

      for (let item of recycleBinDataObjs) {
        item.nr = JSON.parse(item.nr)
      }

      commit(mutation.preplan.setRecycleBinData, recycleBinDataObjs)

      // await evidenceCatalogTree.init();
      // 示证大纲树数据
      // let evidenceCatalogTreeData = await preplanServer.getEvidenceCatalog();
      // if (!evidenceCatalogTreeData) return await dispatch(action.preplan.initEvidenceCatalog);
      // commit(mutation.preplan.initPrePlan, evidenceCatalogTreeData);
    } catch (e) {
      throw e
    }
  },
  async [action.preplan.getCatalogTemplate] ({commit, rootState}) {
    try {
      // let database = await SQLite.ExecuteScalar({SQL: 'select data from tree_template'});
      // fs.writeFileSync('tree_template.json',database)
      // default_template = database ? JSON.parse(database) : [];

      let templateData = L.LocalStore.getTemplateData()
      templateData = templateData || []
      let filter = templateData.filter((x) => x.default)

      if (filter.length) {
        templateData.unshift({
          name: '内置模板',
          id: uuid(),
          data: evidenceCatalogTree.defaultTemplate,
          inlay: true,
          default: false
        })
      } else {
        templateData.unshift({
          name: '内置模板',
          id: uuid(),
          data: evidenceCatalogTree.defaultTemplate,
          inlay: true,
          default: true
        })
      }
      commit(mutation.preplan.SET_CATALOGTEMPLATE, templateData)
    } catch (e) {
      throw e
    }
  },
  async [action.preplan.synch] ({commit, rootState}, data) {
    // let saveArr = data.evidenceCatalog.filter(item => item.id != '-1');

    let result = await preplanServer.saveEvidenceCatalog(JSON.stringify(data))

    if (result) console.log('示证目录更新成功')

    commit(mutation.preplan.initPrePlan, data)
  },
  async [action.preplan.DelDossierFile] ({commit, rootState}, arr) {
    try {
      let obj = {Files: [], Catalogs: [], Type: arr.type}
      for (let i = 0; i < arr.nodes.length; i++) {
        obj[arr.nodes[i].FileType === 'file' ? 'Files' : 'Catalogs'].push(arr.nodes[i].ID)
      }
      await SQLite.DelEvidenceMaterialByCode(obj)
    } catch (e) {
      console.error(e)
      throw e
    }

    // await SQLite.ExecuteNonQuery({
    //   executeSql: sqls
    // })
  },
  async [action.preplan.DelExternalFiles] ({commit, rootState}, arr) {
    let sqls = []
    for (let i = 0; i < arr.length; i++) {
      let file = arr[i]
      if (file.fileID) {
        sqls = sqls.concat(commonSqlHelper.delExternalFile(file.fileID))
      }
    }
    await SQLite.ExecuteNonQuery({
      executeSql: sqls
    })
  },
  async [action.preplan.AddExternalFiles] ({commit, dispatch, rootState}, files) {
    console.log('AddExternalFiles', files)
    if (!files || !Array.isArray(files)) throw new Error('上传本地文件参数错误')

    let preConvert = []
    for (let filePath of files) {
      if (!fs.existsSync(filePath)) throw new Error('本地文件不存在')

      let {base, ext} = path.parse(filePath)

      if (/mp3|mp4/i.test(ext)) {
        // 获取案件路径
        let {dir: fDir, name: fName} = path.parse(rootState.appearCourt.casePath)
        let folderPath = path.resolve(fDir, fName)
        // 案件文件夹不存在时创建
        if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath)
        // 移动文件到案件文件夹下
        let newPath = path.resolve(folderPath, base)
        await copyFileSync(filePath, newPath)
        preConvert.push(newPath)
      } else {
        preConvert.push(filePath)
      }
    }

    try {
      return await SQLite.DocumentConvertToImage(preConvert)
    } catch (e) {
      throw e
    }
  },
  async [action.preplan.SetChapterTemplate] ({commit, dispatch, rootState}, value) {
    commit(mutation.preplan.SetChapterTemplate, value)
  },
  async [action.preplan.addRecycleBinData] ({commit, dispatch, rootState}, recycleBinData) {
    let recycleBinDataObj = {
      id: uuid(),
      nr: [recycleBinData],
      cjsj: new Date().Format('yyyy-MM-dd hh:mm:ss')
    }

    if (process.browser) {
      await SQLite.ExecuteNonQuery({
        SQL: `insert into yx_ya_hsz(id,nr,cjsj) values(?,?,?)`,
        parameter: {
          1: recycleBinDataObj.id,
          2: JSON.stringify(recycleBinDataObj.nr),
          3: recycleBinDataObj.cjsj
        }
      })
    } else {
      await SQLite.ExecuteNonQuery({
        executeSql: [{
          SQL: `insert into yx_ya_hsz(id,nr,cjsj) values($id,$nr,$cjsj)`,
          Parameter: {
            $id: recycleBinDataObj.id,
            $nr: JSON.stringify(recycleBinDataObj.nr),
            $cjsj: recycleBinDataObj.cjsj
          }
        }]
      })
    }

    commit(mutation.preplan.addRecycleBinData, recycleBinDataObj)
  },
  async [action.preplan.clearRecycleBinData] ({commit, dispatch, rootState}, recycleBinData) {
    try {
      await SQLite.ExecuteNonQuery({
        executeSql: [{
          SQL: `delete from yx_ya_hsz where id=$id`,
          Parameter: {
            $id: recycleBinData.id
          }
        }]
      })

      commit(mutation.preplan.clearRecycleBinData, recycleBinData)
    } catch (e) {
      throw e
    }
  }
}

const getters = {
  catalogML: (state, getter, store) => {
    return getCatalogML(JSON.parse(JSON.stringify(state.evidenceCatalogTreeData)))
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
